﻿using System.Text;
using LY.Business.ServiceImpl;
using LY.Common;
using LY.Common.Utils;
using LY.Common.Utils.Sf_Struct;
using LY.Common.Utils.Sign;
using LY.Common.Utils.YeePay;
using LY.Common.Utils.YeePayUtil;
using LY.Entity;
using LY.Entity.Entities;
using LY.Extension;
using LY.Interface;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;
using System.Xml.Linq;

namespace QJ.CMS.Controllers
{
    public class PayController : MyControllerBase
    {
        private ILogService _logService;
        private IFundsFlowService _fservice;
        private ILoginService _lService;
        private IInvestService _iservice;
        private IProjectService _pservice;
        private IBankInfoService _bankInfo;
        private IT_RepaymentPlanService _repaymentService;
        private IT_ProjectService _tpservice;
        private IReFundService _reFundService;
        private IScoreService _scoreService;
        private IClaimsService _cservice;
        private IMemberService _memberservice;
        private static string _merchantNo = ConfigurationManager.AppSettings["merchantNo"];
        private static string _backAddress = ConfigurationManager.AppSettings["BackAddress"];
        private static string _apiAddress = ConfigurationManager.AppSettings["ApiAddress"];

        private static string _zqFee = ConfigurationManager.AppSettings["ZQFee"];

        public PayController(ILogService lService, IFundsFlowService fService, ILoginService loginService, IInvestService iService, IProjectService pService
            , IBankInfoService bankInfo, IT_RepaymentPlanService repaymentService, IT_ProjectService tpservice, IReFundService reFundService, IScoreService sSercice
            , IClaimsService cSercive, IMemberService memberservice)
        {
            _logService = lService;
            _fservice = fService;
            _lService = loginService;
            _iservice = iService;
            _pservice = pService;
            _bankInfo = bankInfo;
            _repaymentService = repaymentService;
            _tpservice = tpservice;
            _reFundService = reFundService;
            _scoreService = sSercice;
            _cservice = cSercive;
            _memberservice = memberservice;
        }

        #region 盛付通充值异步返回
        //盛付通充值后的NotifyUrl异步通知地址
        public void RechargeNotifyUrl()
        {
            MyLog.Write("充值异步返回开始"); 
            string queryString = Request["Name"] + "|" + Request["Version"] + "|" + Request["Charset"] + "|" + Request["TraceNo"] + "|"
                + Request["MsgSender"] + "|" + Request["SendTime"] + "|" + Request["InstCode"] + "|" + Request["OrderNo"] + "|"
                + Request["OrderAmount"] + "|" + Request["TransNo"] + "|" + Request["TransAmount"] + "|" + Request["TransStatus"] + "|"
                + Request["TransType"] + "|" + Request["TransTime"] + "|" + Request["MerchantNo"] + "|" + Request["SignType"] + "|";

            MyLog.WriteLog("充值异步返回", queryString.Replace("&", "\r"));
            MySign mysign = new MySign();
            bool result = mysign.ValidateSign(queryString, Request["SignMsg"]);
            if (result)
            {
                try
                {
                    U_FundsFlow fundsflow = _fservice.GetFundsFlowByOrderNo(Request["OrderNo"]);
                    U_BankInfo bankInfo = _bankInfo.GetBankInfo(Request["InstCode"]);
                    fundsflow.BankId = bankInfo.Id;
                    fundsflow.BankName = bankInfo.BankName;
                    var statusMsg = "充值成功";
                    if (Request["TransStatus"] == "01") //表示付款成功
                    {
                        fundsflow.Status = 1; 
                        //发送短信 
                        ISysTemplateService templateService = new SysTemplateService();
                        var templateModel = templateService.GetSysTemplate("chongzhi");
                        string smstemp = templateModel.TemplateContent;
                        smstemp = smstemp.Replace("{Amount}", Request["TransAmount"]);
                        smstemp = smstemp.Replace("{orderNo}", Request["OrderNo"]);
                        smstemp = smstemp.Replace("{statusMsg}", statusMsg);
                        var msg = string.Empty;
                        IMemberService memberService = new MemberService();
                        var member = memberService.getMemberInfo(fundsflow.MemberId);
                        //发送验证码   
                        var flag = SmsMessage.Send(member.Mobilenumber, smstemp, 1, out msg);
                    }
                    else
                    {
                        fundsflow.Status = -1;
                        statusMsg = "充值失败";
                    }
                    fundsflow.AuditTime = DateTime.Now;
                    int i = _fservice.UpdateFundsFlow(fundsflow);
                }
                catch (Exception ex)
                {
                    MyLog.Write(Request["OrderNo"]); 
                    MyLog.Write(ex.ToString());
                }
                Response.StatusCode = 200;
                Response.Write("OK");
            }
            else
            {
                MyLog.Write("充值的异步验证失败了");
            }
        }
        #endregion

        #region 盛付通提现的异步返回
        //盛付通提现的异步返回 测试环境下是需要对方配合主动发
        public void WithdrawNotifyUrl()
        {
            //验证签名
            MyLog.Write("提现异步返回开始");
            //MyLog.Write(Request["withdrawNo"]);
            //MyLog.Write(Request["amount"]);
            //MyLog.Write(Request["fee"]);
            //MyLog.Write(Request["result"]);
            //MyLog.Write(Request["sign"]);
            string quertString = "" + "amount=" + Request["amount"] + "&fee=" + Request["fee"] + "&result=" + Request["result"] +
                "&withdrawNo=" + Request["withdrawNo"];
            MySign mysign = new MySign();
            bool result = mysign.ValidateSign(quertString, Request["sign"]);
            if (result)
            {
                try
                {
                    if (Request["result"] == "3" || Request["result"] == "1") //没有收到2和4则表示成功
                    {
                        U_FundsFlow fundsflow = _fservice.GetFundsFlowByOrderNo(Request["withdrawNo"], 2); //获取提现的那条记录
                        fundsflow.Status = 1;
                        fundsflow.AuditTime = DateTime.Now;

                        U_FundsFlow fundsflow2 = _fservice.GetFundsFlowByOrderNo(Request["withdrawNo"], 6); //获取提现的手续费
                        fundsflow2.Status = 1;
                        fundsflow2.AuditTime = DateTime.Now;

                        int i = _fservice.UpdateFundsFlow(fundsflow);
                        int j = _fservice.UpdateFundsFlow(fundsflow2);

                        //发送短信
                        ISysTemplateService templateService = new SysTemplateService();
                        var templateModel = templateService.GetSysTemplate("withdraw");
                        string smstemp = templateModel.TemplateContent;
                        smstemp = smstemp.Replace("{Amount}", Request["amount"]);
                        smstemp = smstemp.Replace("{factorage}", Request["fee"]);
                        smstemp = smstemp.Replace("{orderNo}", Request["withdrawNo"]);
                        
                        var msg = string.Empty;
                        IMemberService memberService = new MemberService();
                        U_Member member = memberService.getMemberInfo(fundsflow.MemberId);
                        //发送验证码   
                        var flag = SmsMessage.Send(member.Mobilenumber, smstemp, 1, out msg);
                    }
                    else
                    {
                        U_FundsFlow fundsflow = _fservice.GetFundsFlowByOrderNo(Request["withdrawNo"], 2); //获取提现的那条记录
                        fundsflow.Status = 0;
                        fundsflow.AuditTime = DateTime.Now;

                        U_FundsFlow fundsflow2 = _fservice.GetFundsFlowByOrderNo(Request["withdrawNo"], 6); //获取提现的手续费
                        fundsflow2.Status = 0;
                        fundsflow2.AuditTime = DateTime.Now;

                        int i = _fservice.UpdateFundsFlow(fundsflow);
                        int j = _fservice.UpdateFundsFlow(fundsflow2);
                    }
                    

                }
                catch (Exception ex)
                {
                    MyLog.Write(ex.ToString());
                    MyLog.Write(Request["withdrawNo"]);
                    MyLog.Write(Request["amount"]);
                    MyLog.Write(Request["fee"]);
                    MyLog.Write(Request["result"]);
                    MyLog.Write(Request["sign"]);
                }
                Response.StatusCode = 200;
                Response.Write("OK");
            }
            else
            {
                MyLog.Write("提现异步验证失败");
            }
        }
        #endregion

        #region 盛付通众筹Api投标的异步返回接口
        public void OrderConfirmApiNotifyUrl()
        {
            //验证签名
            string quertString = "" + "creditAmount=" + Request["creditAmount"] + "&creditUserName=" +
                                 Request["creditUserName"] +
                                 "&discountAmount=" + Request["discountAmount"] + "&issueBidNo=" + Request["issueBidNo"] +
                                 "&merchantNo=" + Request["merchantNo"] +
                                 "&notifyTime=" + Request["notifyTime"] + "&notifyType=" + Request["notifyType"] +
                                 "&result=" + Request["result"] + "&submitBidNo=" + Request["submitBidNo"];
            MySign mysign = new MySign();
            bool myresult = mysign.ValidateSign(quertString, Request["sign"]);
            if (myresult)
            {
                MyLog.Write("验证自动投标API接口返回成功");
                try //获取刚刚订单表里面的记录
                {
                    //if (_fservice.CheckOrderNo(Request["submitBidNo"]) <= 0)//数据库中没有存储
                    //{
                    //    U_FundsFlow fundsflow = new U_FundsFlow();
                    //    U_Member mm = (U_Member)Session["CurrentUser"];
                    //    fundsflow.Type = 3;//暂时定义为这个，忘了。3表示投标，投资
                    //    fundsflow.MemberId = mm.ID;
                    //    fundsflow.OrderNo = Request["submitBidNo"];
                    //    fundsflow.CreateTime = DateTime.Now;
                    //    int i = _fservice.BiaoFundsFlow(fundsflow);
                    //}
                    //else
                    //{
                    //    U_FundsFlow fundsflow = _fservice.GetFundsFlowByOrderNo(Request["submitBidNo"]);
                    //    fundsflow.OutPay = decimal.Parse(Request["creditAmount"]);
                    //    fundsflow.AuditTime = DateTime.Now;
                    //    fundsflow.Status = 1;
                    //    int j = _fservice.BiaoFundsFlow(fundsflow);
                    //}
                    //修改订单的状态
                    R_ProjectOrder projectOrder = _pservice.GerProjectOrderBySerialNumber(Request["submitBidNo"]);
                    projectOrder.PayTime = DateTime.Now;
                    projectOrder.PayType = 1;
                    projectOrder.PayStatus = 1;
                    int i = _pservice.SaveProjectOrder(projectOrder);
                    //修改资金流的状态
                    U_FundsFlow fundsflow = _fservice.GetFundsFlowByOrderNo(Request["submitBidNo"], 3);//获取提现的那条记录
                    fundsflow.Status = 1;
                    fundsflow.AuditTime = DateTime.Now;
                    int j = _fservice.UpdateFundsFlow(fundsflow);

                }
                catch (Exception ex)
                {
                    MyLog.Write(ex.ToString());
                    MyLog.Write("notifyType = " + Request["notifyType"]);
                    MyLog.Write("notifyTime = " + Request["notifyTime"]);
                    MyLog.Write("merchantNo = " + Request["merchantNo"]);
                    MyLog.Write("issueBidNo = " + Request["issueBidNo"]);
                    MyLog.Write("submitBidNo = " + Request["submitBidNo"]);
                    MyLog.Write("creditUserName = " + Request["creditUserName"]);
                    MyLog.Write("creditAmount = " + Request["creditAmount"]);
                    MyLog.Write("discountAmount = " + Request["discountAmount"]);
                    MyLog.Write("result = " + Request["result"]);
                    MyLog.Write("result = " + Request["timestamp"]);
                    MyLog.Write("sign = " + Request["sign"]);
                }
                Response.StatusCode = 200;
                Response.Write("OK");
            }
            else
            {
                MyLog.Write("验证数据失败了啊");
            }
        }
        #endregion

        #region 满标的异步返回
        //满标的异步返回 ManBiaoNotifyUrl
        public ActionResult ManBiaoNotifyUrl()
        {
            MyLog.Write("满标异步返回开始");
            //MyLog.Write(Request["issueBidNo"]);
            //MyLog.Write(Request["debitUserName"]);
            //MyLog.Write(Request["debitAmount"]);
            //MyLog.Write(Reque st["notifyType"]);
            //MyLog.Write(Request["result"]);
            //MyLog.Write(Request["transTime"]);
            //MyLog.Write(Request["transferItems"]);
            //MyLog.Write(Request["sign"]);
            //验证签名
            string quertString = "" + "debitAmount=" + Request["debitAmount"] + "&debitUserName=" + Request["debitUserName"] +
                "&issueBidNo=" + Request["issueBidNo"] + "&notifyType=" + Request["notifyType"] + "&result=" + Request["result"] +
                "&transTime=" + Request["transTime"] + "&transferItems=" + Request["transferItems"];
            MySign mysign = new MySign();
            bool result = mysign.ValidateSign(quertString, Request["sign"]);
            if (result) //这里Request["result"]固定是success
            {
                MyLog.Write("验证正确");
                T_Project project = _tpservice.GetModelByProjectNo(Request["issueBidNo"]);
                project.LoanStatus = 1;
                project.LoanTime = DateTime.Now;
                _tpservice.SaveModel(project);
                //项目还款计划列表 GetRPListByProID
                //List<T_RepaymentPlan_EX> RepPlanList = _repo.QueryRepPlanList(project.ID);
                List<T_RepaymentPlan_EX> RepPlanList = _tpservice.GetRPListByProID(project.ID);
                DateTime repPlanDate = DateTime.Now;
                int status = 1;
                for (int i = 0; i < RepPlanList.Count; i++)
                {
                    if (i == 0)
                    {
                        status = 2;
                    }
                    if (project.DurationMonthOrDay == 1)
                    {
                        //月份
                        //生成项目收益日期
                        _tpservice.UpdateRepPlanDate(RepPlanList[i].ID, repPlanDate.AddMonths(i + 1), status);
                    }
                    else if (project.DurationMonthOrDay == 2)
                    {
                        //天数
                        repPlanDate.AddDays((int)project.ProjectDuration);
                        _tpservice.UpdateRepPlanDate(RepPlanList[i].ID, repPlanDate.AddDays((int)project.ProjectDuration), status);
                    }
                }

                TransferItems[] dic = new JavaScriptSerializer().Deserialize<TransferItems[]>(Request["transferItems"]);
                decimal countAmount = 0;
                for (int i = 0; i < dic.Length;i++ )
                {
                    countAmount = countAmount + decimal.Parse(dic[i].amount);
                }

                //满标之后把所有的钱全部汇入到借款人，需要添加借款人资金流
                U_FundsFlow fundsflow = new U_FundsFlow();
                U_Member member = _memberservice.GetModelBySftUserName(Request["debitUserName"]);
                fundsflow.OrderNo = Request["issueBidNo"];
                fundsflow.MemberId = member.ID;
                fundsflow.InCome = countAmount;//这里是所有投资人的金额加起来，因为有时是手动满标,虽然暂时没有这种情况。
                fundsflow.CreateTime = DateTime.Now;
                fundsflow.Status = 1;
                fundsflow.Type = 11;
                fundsflow.ProjectId = project.ID;
                _fservice.InsertFundsFlow(fundsflow);
                Response.StatusCode = 200;
                Response.Write("OK");
            }
            else
            {
                MyLog.Write("验证失败");
            }
            MyLog.Write("满标异步返回结束");
            return null;
        }
        #endregion

        #region 流标的异步返回
        public ActionResult LiuBiaoNotifyUrl()
        {
            MyLog.Write("流标异步返回开始aaaa");
            MyLog.Write(Request["issueBidNo"]);
            MyLog.Write(Request["debitUserName"]);
            MyLog.Write(Request["debitAmount"]);
            MyLog.Write(Request["notifyType"]);
            MyLog.Write(Request["result"]);
            MyLog.Write(Request["transTime"]);
            MyLog.Write(Request["sign"]);
            //验证签名
            string quertString = "" + "debitAmount=" + Request["debitAmount"] + "&debitUserName=" +
                                 Request["debitUserName"] +
                                 "&issueBidNo=" + Request["issueBidNo"] + "&notifyType=" + Request["notifyType"] +
                                 "&result=" + Request["result"] +
                                 "&transTime=" + Request["transTime"];
            MySign mysign = new MySign();
            bool result = mysign.ValidateSign(quertString, Request["sign"]);
            if (result)
            {
                MyLog.Write("验证正确");
                T_Project project = _tpservice.GetModelByProjectNo(Request["issueBidNo"]);
                project.TenderStatus = 2;//流标
                _tpservice.SaveModel(project);
                //流标之后将钱还给投资人需要添加资金流，因为当前获取不到明细记录，所以只能先查询出原来的投资记录，然后在添加进去
                _fservice.LiuBiaoHandel(project.ID);
                Response.StatusCode = 200;
                Response.Write("OK");
            }
            else
            {

            }
            MyLog.Write(quertString);
            MyLog.Write("流标异步返回结束bbbb");
            return null;
        }
        #endregion

        #region 盛付通债权投标Web异步返回接口
        public void ZhaiQuanConfirmNotifyUrl()
        {
            //验证签名
            MyLog.Write(Request["discountAmount"]);
            string quertString = "" + "creditAmount=" + Request["creditAmount"] + "&creditUserName=" + Request["creditUserName"] + "&discountAmount=" + Request["discountAmount"] +
                "&issueBidNo=" + Request["issueBidNo"] + "&merchantNo=" + Request["merchantNo"] + "&notifyTime=" + Request["notifyTime"]
                + "&notifyType=" + Request["notifyType"] + "&result=" + Request["result"] + "&submitBidNo=" + Request["submitBidNo"];

            MyLog.WriteLog("债权投标异步返回" + Request["issueBidNo"], quertString.Replace("&", "\r"));

            MySign mysign = new MySign();
            bool myresult = mysign.ValidateSign(quertString, Request["sign"]);
            if (myresult)
            {
                MyLog.Write("债权投标Web异步返回验证数据成功");
                if (Request["result"] == "success")
                {
                    try //获取刚刚订单表里面的记录
                    {
                        U_FundsFlow fundsflow = _fservice.GetFundsFlowByOrderNo(Request["submitBidNo"], 4);//获取投债权的那条记录
                        T_Investment investment = _iservice.GetModelBySubmitBidNo(Request["submitBidNo"]);
                        var project = _cservice.GetProjectById(investment.ProjectId.ToString());
                        var amounts = _cservice.GetAmountsByPid(investment.ProjectId.ToString());
                        decimal avaAmounts;
                        if (investment.Status==1)
                        {
                            avaAmounts = (decimal)project.TotalLoan - amounts;
                        }
                        else
                        {
                            avaAmounts = (decimal)project.TotalLoan - amounts - investment.TenderAmt;
                        }
                        if (avaAmounts <= 0)
                        {
                            //这里又又又改成了手动满标了哎
                            project.TenderStatus = 1;
                            project.TenderTime = DateTime.Now;
                            _tpservice.SaveModel(project);
                            //string notifyUrl = _backAddress + "/Pay/ManBiaoNotifyUrl";
                            //if (project.TenderStatus==0) //没有满标
                            //{
                            //    string strJson = LY.ShengPayApi.Services.Put.PutP2PBidEvent(_merchantNo, project.ProjectNo, 2, notifyUrl, "0.00", _apiAddress);
                            //    project.TenderStatus = 1;
                            //    project.TenderTime = DateTime.Now;
                            //    _tpservice.SaveModel(project);
                            //}
                        }
                        //修改资金流的状态
                        fundsflow.Status = 1;
                        fundsflow.AuditTime = DateTime.Now;
                        int j = _fservice.UpdateFundsFlow(fundsflow);
                        //修改投资记录表的状态
                        investment.Status = 1;
                        _iservice.SaveInvestment(investment);
                        _scoreService.SaveScore("债权投资", fundsflow.MemberId, (int)investment.TenderAmt);
                        if (Convert.ToDouble(Request["discountAmount"]) > 0)
                        {
                            _scoreService.SaveScore("积分抵扣", fundsflow.MemberId, -(int)(Convert.ToDouble(Request["discountAmount"]) * 100));
                        }


                        //发送短信
                        ISysTemplateService templateService = new SysTemplateService();
                        var templateModel = templateService.GetSysTemplate("touzi");
                        string smstemp = templateModel.TemplateContent;
                        smstemp = smstemp.Replace("{Amount}", Request["creditAmount"]);
                        smstemp = smstemp.Replace("{orderNo}", Request["submitBidNo"]);
                        smstemp = smstemp.Replace("{statusMsg}", "投资成功");
                      
                        var msg = string.Empty;
                        IMemberService memberService = new MemberService();
                        var member = memberService.getMemberInfo(fundsflow.MemberId);
                        //发送验证码   
                        var flag = SmsMessage.Send(member.Mobilenumber, smstemp, 1, out msg);

                    }
                    catch (Exception ex)
                    {
                        MyLog.Write(ex.ToString());
                        MyLog.Write("notifyType = " + Request["notifyType"]);
                        MyLog.Write("notifyTime = " + Request["notifyTime"]);
                        MyLog.Write("merchantNo = " + Request["merchantNo"]);
                        MyLog.Write("issueBidNo = " + Request["issueBidNo"]);
                        MyLog.Write("submitBidNo = " + Request["submitBidNo"]);
                        MyLog.Write("creditUserName = " + Request["creditUserName"]);
                        MyLog.Write("creditAmount = " + Request["creditAmount"]);
                        MyLog.Write("discountAmount = " + Request["discountAmount"]);
                        MyLog.Write("result = " + Request["result"]);
                        MyLog.Write("sign = " + Request["sign"]);
                    }
                }
                else //异步的返回失败，表示真的失败了
                {
                    U_FundsFlow fundsflow = _fservice.GetFundsFlowByOrderNo(Request["submitBidNo"], 4);
                    fundsflow.Status = 0;
                    fundsflow.AuditTime = DateTime.Now;
                    int j = _fservice.UpdateFundsFlow(fundsflow);
                    T_Investment investment = _iservice.GetModelBySubmitBidNo(Request["submitBidNo"]);
                    investment.Status = 0;
                    _iservice.SaveInvestment(investment);

                    ISysTemplateService templateService = new SysTemplateService();
                    var templateModel = templateService.GetSysTemplate("touzi");
                    string smstemp = templateModel.TemplateContent;
                    smstemp = smstemp.Replace("{Amount}", Request["creditAmount"]);
                    smstemp = smstemp.Replace("{orderNo}", Request["submitBidNo"]);
                    smstemp = smstemp.Replace("{statusMsg}", "投资失败");

                    var msg = string.Empty;
                    IMemberService memberService = new MemberService();
                    var member = memberService.getMemberInfo(fundsflow.MemberId);
                    //发送验证码   
                    var flag = SmsMessage.Send(member.Mobilenumber, smstemp, 1, out msg);
                }
                Response.StatusCode = 200;
                Response.Write("OK");
            }
            else
            {
                MyLog.Write("验证数据失败了啊");
            }
        }

        

        #endregion

        #region 盛付通债权投标API的异步返回接口
        public void ZhaiQuanConfirmApiNotifyUrl()
        {
            //验证签名
            string quertString = "" + "creditAmount=" + Request["creditAmount"] + "&creditUserName=" +
                                 Request["creditUserName"] +
                                 "&discountAmount=" + Request["discountAmount"] + "&issueBidNo=" + Request["issueBidNo"] +
                                 "&merchantNo=" + Request["merchantNo"] +
                                 "&notifyTime=" + Request["notifyTime"] + "&notifyType=" + Request["notifyType"] +
                                 "&result=" + Request["result"] + "&submitBidNo=" + Request["submitBidNo"];
            MySign mysign = new MySign();
            bool myresult = mysign.ValidateSign(quertString, Request["sign"]);
            if (myresult)
            {
                MyLog.Write("债权投标异步数据返回成功");
                if (Request["result"] == "success")
                {
                    try
                    {
                        //修改资金流的状态
                        U_FundsFlow fundsflow = _fservice.GetFundsFlowByOrderNo(Request["submitBidNo"], 4); //获取提现的那条记录
                        fundsflow.Status = 1;
                        fundsflow.AuditTime = DateTime.Now;
                        int j = _fservice.UpdateFundsFlow(fundsflow);
                        T_Investment investment = _iservice.GetModelBySubmitBidNo(Request["submitBidNo"]);
                        investment.Status = 1;
                        _iservice.SaveInvestment(investment);
                    }
                    catch (Exception ex)
                    {
                        MyLog.Write(ex.ToString());
                        MyLog.Write("notifyType = " + Request["notifyType"]);
                        MyLog.Write("notifyTime = " + Request["notifyTime"]);
                        MyLog.Write("merchantNo = " + Request["merchantNo"]);
                        MyLog.Write("issueBidNo = " + Request["issueBidNo"]);
                        MyLog.Write("submitBidNo = " + Request["submitBidNo"]);
                        MyLog.Write("creditUserName = " + Request["creditUserName"]);
                        MyLog.Write("creditAmount = " + Request["creditAmount"]);
                        MyLog.Write("discountAmount = " + Request["discountAmount"]);
                        MyLog.Write("result = " + Request["result"]);
                        MyLog.Write("result = " + Request["timestamp"]);
                        MyLog.Write("sign = " + Request["sign"]);
                    }
                    Response.StatusCode = 200;
                    Response.Write("OK");
                }
                else //异步返回错误表示投标失败
                {
                    U_FundsFlow fundsflow = _fservice.GetFundsFlowByOrderNo(Request["submitBidNo"], 4); //获取提现的那条记录
                    fundsflow.Status = 0;
                    fundsflow.AuditTime = DateTime.Now;
                    int j = _fservice.UpdateFundsFlow(fundsflow);
                    T_Investment investment = _iservice.GetModelBySubmitBidNo(Request["submitBidNo"]);
                    investment.Status = 0;
                    _iservice.SaveInvestment(investment);
                }
            }
            else
            {
                MyLog.Write("验证数据失败了啊");
            }
        }
        #endregion

        #region 个人还款Web异步返回接口
        public ActionResult RepaymentnotifyUrl()
        {
            MyLog.Write("个人还款开始");
            MyLog.Write(Request["issueBidNo"]);
            MyLog.Write(Request["borrowUserName"]);
            MyLog.Write(Request["repaymentNo"]);
            MyLog.Write(Request["repaymentAmount"]);
            MyLog.Write(Request["transferItems"]);
            MyLog.Write(Request["notifyType"]);
            MyLog.Write(Request["result"]);
            MyLog.Write(Request["transTime"]);
            MyLog.Write(Request["sign"]);
            //验证签名
            string quertString = "borrowUserName=" + Request["borrowUserName"]
                                    + "&issueBidNo=" + Request["issueBidNo"] + "&notifyType=" + Request["notifyType"]
                                    + "&repaymentAmount=" + Request["repaymentAmount"] + "&repaymentNo=" + Request["repaymentNo"]
                                    + "&result=" + Request["result"] + "&transTime=" + Request["transTime"]
                                    + "&transferItems=" + Request["transferItems"];
            MySign mysign = new MySign();
            bool myresult = mysign.ValidateSign(quertString, Request["sign"]);
            if (myresult)
            {
                MyLog.Write("验证成功");
                if (Request["result"] == "success")
                {
                    try//修改数据的状态
                    {
                        //先把自己的金额减吊啊
                        U_FundsFlow fundsFlow = new U_FundsFlow();
                        U_Member member = _memberservice.GetModelBySftUserName(Request["borrowUserName"]);
                        fundsFlow.OrderNo = Request["origOrderNo"];
                        fundsFlow.MemberId = member.ID;
                        fundsFlow.InCome = decimal.Parse("0.00");
                        fundsFlow.OutPay = decimal.Parse(Request["repaymentAmount"]);
                        fundsFlow.CreateTime = DateTime.Now;
                        fundsFlow.Status = 1;
                        fundsFlow.Type = 10;
                        _fservice.InsertFundsFlow(fundsFlow);
                        
                        TransferItems[] dic;
                        dic = new JavaScriptSerializer().Deserialize<TransferItems[]>(Request["transferItems"]);

                        T_RepaymentPlan repaymentPlan = _repaymentService.GetModelByRepaymentPlanNo(Request["repaymentNo"]);
                        int ret;
                        string name = "quanju"; //这个变量暂时没用到
                        double CurrentPrincipal = _tpservice.getRemainingPrincipal(repaymentPlan.ID);//查询剩余资金，sql语句写的是查询剩余资金，
                        if (CurrentPrincipal == 0)//但是这里的变量写的是当前资金？？？
                        {
                            ret = _iservice.SaveRept(repaymentPlan.ProjectID, name, 0, Convert.ToDouble(_zqFee));//这一步就是充值是利息
                            ret = _iservice.SaveReptPrincipal(repaymentPlan.ProjectID, name, 0, 0);//这一步也是充值是本金
                            if (ret > 0)
                            {
                                ret = _tpservice.ChangeRept(repaymentPlan.ProjectID, name);//修改项目表T_Project的RepaymentStatus=1
                            }
                        }
                        else
                        {
                            ret = _iservice.SaveRept(repaymentPlan.ProjectID, name, 0, 0);//还利息的时候就把利息存入到资金记录表，当做借款人的收益。
                        }
                        if (ret > 0)
                        {
                            ret = _tpservice.RepaymentPlan(repaymentPlan.ID);//将还款记录表的状态改为3
                        }
                    }
                    catch (Exception ex)
                    {
                        MyLog.Write(ex.ToString());
                    }
                }
                Response.StatusCode = 200;
                Response.Write("OK");
            }
            else
            {
                MyLog.Write("验证失败");
            }
            return null;
        }
        #endregion

        #region 盛付通平台分批放款异步返回接口
        /// <summary>
        /// 盛付通平台分批放款异步返回接口
        /// </summary>
        /// <returns></returns>
        public ActionResult LoanNotifyUrl()
        {
            string quertString = "" + "origOrderType=" + Request["origOrderType"] + "&origOrderNo=" +
                            Request["origOrderNo"] +
                            "&loanAmount=" + Request["loanAmount"] + "&notifyType=" + Request["notifyType"] +
                            "&result=" + Request["result"] +
                            "&transTime=" + Request["transTime"];
            MySign mysign = new MySign();
            bool result = mysign.ValidateSign(quertString, Request["sign"]);
            if (result)
            {
                MyLog.Write("验证正确");
                Response.StatusCode = 200;
                Response.Write("OK");
            }
            else
            {

            }
            MyLog.Write(quertString);
            return null;
        }
        #endregion

        #region Web跳转
        public ActionResult GoShengPay()
        {
            return View();
        }
        #endregion

        #region 众筹新支付接口异步返回
        public void OrderConfirmNotifyUrl()
        {
            //验证签名
            var  strlog = new StringBuilder();
 
                strlog.Append("Name=" + Request["Name"]);
                strlog.Append("Version=" + Request["Version"]);
                 strlog.Append("Charset=" + Request["Charset"]);
                 strlog.Append("TraceNo=" + Request["TraceNo"]);
                 strlog.Append("MsgSender=" + Request["MsgSender"]);
                 strlog.Append("SendTime=" + Request["SendTime"]);
                 strlog.Append("InstCode=" + Request["InstCode"]);
                 strlog.Append("OrderNo=" + Request["OrderNo"]);
                 strlog.Append("OrderAmount=" + Request["OrderAmount"]);
                 strlog.Append("TransNo=" + Request["TransNo"]);
                 strlog.Append("TransAmount=" + Request["TransAmount"]);
                 strlog.Append("TransStatus=" + Request["TransStatus"]);
                 strlog.Append("TransType=" + Request["TransType"]);
                 strlog.Append("TransTime=" + Request["TransTime"]);
                 strlog.Append("MerchantNo=" + Request["MerchantNo"]);
                 strlog.Append("ErrorCode=" + Request["ErrorCode"]);
                 strlog.Append("ErrorMsg=" + Request["ErrorMsg"]);
                 strlog.Append("Ext1=" + Request["Ext1"]);
                 strlog.Append("BankSerialNo=" + Request["BankSerialNo"]);
                 strlog.Append("RequestCurrency=" + Request["RequestCurrency"]);
                 strlog.Append("PaymentCurrency=" + Request["PaymentCurrency"]);
                 strlog.Append("RequestOrderAmount=" + Request["RequestOrderAmount"]);
                 strlog.Append("FexchangeRate=" + Request["FexchangeRate"]);
                 strlog.Append("SignType=" + Request["SignType"]);
                 strlog.Append("SignMsg=" + Request["SignMsg"]);
                 MyLog.WriteLog("众筹新支付接口异步返回开始", strlog.ToString());
            try 
            {
                string orderNo = Request["OrderNo"];
                string TraceNo = Request["TraceNo"]; //请求序列号 报文发起方唯一消息标识
                string transNo = Request["TransNo"]; //盛付通交易号
                string BankSerialNo = Request["BankSerialNo"];//网银流水号
                string transStatus = Request["TransStatus"];
                if (Request["TransStatus"] == "01")
                {
                    //修改订单的状态
                    R_ProjectOrder projectOrder = _pservice.GerProjectOrderBySerialNumber(Request["OrderNo"]);
                    projectOrder.PayTime = DateTime.Now;
                    projectOrder.PayType = 1;
                    projectOrder.PayStatus = 1;
                    int i = _pservice.SaveProjectOrder(projectOrder);
                    //修改资金流的状态
                    U_FundsFlow fundsflow = _fservice.GetFundsFlowByOrderNo(Request["OrderNo"], 3);
                    fundsflow.Status = 1;
                    fundsflow.AuditTime = DateTime.Now;
                    int j = _fservice.UpdateFundsFlow(fundsflow);
                }
            }
            catch (Exception ex)
            {
                MyLog.Write(ex.ToString());
            }
            Response.StatusCode = 200;
            Response.Write("OK");
        }
        #endregion

        #region 众筹新退款接口的异步返回
        public void ReFundNotifyUrl()
        {
            //验证签名
            MyLog.Write("众筹新退款接口的异步返回");
            string origin = Request["ServiceCode"] + "|" + Request["Version"] + "|"
                            + Request["Charset"] + "|" + Request["TraceNo"] + "|" + Request["SenderId"] + "|"
                            + Request["SendTime"] + "|" + Request["RefundOrderNo"] + "|" + Request["OriginalOrderNo"] + "|"
                            + Request["Status"] + "|" + Request["RefundAmount"] + "|" + Request["RefundTransNo"] + "|"
                            + Request["SignType"] + "|";
            if (Request["errorMsg"] == "原始订单状态不是支付成功，不允许退款！")
            {
                MyLog.Write("原始订单状态不是支付成功，不允许退款！");
                return;
            }
            if (MD5Util.GetMD5_32(origin + "abcdefg").ToUpper() == Request["SignMsg"])
            {
                MyLog.Write("众筹新退款接口的异步返回数据验证成功");
                try
                {
                    //修改订单状态
                    R_ProjectOrder order = _pservice.GerProjectOrderBySerialNumber(Request["OriginalOrderNo"]);
                    R_ReFund reFund = new R_ReFund();
                    switch (Request["Status"])
                    {
                        case "00": order.PayStatus = 5; break;
                        case "01": order.PayStatus = 6; break;
                        case "02": order.PayStatus = 7; break;
                    }
                    _pservice.SaveProjectOrder(order);
                    //将原来这条资金流修改为0
                    U_FundsFlow oldFundsFlow = _fservice.GetFundsFlowByOrderNo(Request["OriginalOrderNo"]);
                    oldFundsFlow.Status = 0;
                    _fservice.UpdateFundsFlow(oldFundsFlow);
                    reFund.MemberId = order.MemberId;
                    reFund.ProjectId = order.ProjectId;
                    reFund.ProjectItemId = order.ProjectItemId;
                    reFund.TraceNo = Request["TraceNo"];
                    reFund.SenderId = Request["SenderId"];
                    reFund.SendTime = DateTime.Now;
                    reFund.RefundOrderNo = Request["RefundOrderNo"];
                    reFund.OriginalOrderNo = Request["OriginalOrderNo"];
                    reFund.Status = Request["Status"];
                    reFund.RefundAmount = Request["RefundAmount"];
                    reFund.RefundTransNo = Request["RefundTransNo"];
                    int i = _reFundService.AddReFund(reFund);
                    //添加资金流的状态
                    U_FundsFlow fundsflow = new U_FundsFlow();
                    fundsflow.OrderNo = Request["OriginalOrderNo"];
                    fundsflow.MemberId = (int)order.MemberId;
                    fundsflow.InCome = Convert.ToDecimal(Request["RefundAmount"]);
                    fundsflow.CreateTime = DateTime.Now;
                    fundsflow.Status = 1;
                    fundsflow.Type = 9;//众筹退款
                    fundsflow.ProjectId = order.ProjectId;
                    fundsflow.AuditTime = DateTime.Now;
                    int j = _fservice.InsertFundsFlow(fundsflow);
                    //这里调用接口
                    ISysTemplateService _templateService = new SysTemplateService();
                    var templateModel = _templateService.GetSysTemplate("apply_refund");
                    //：{code}，{valid}
                    //重新赋值
                    string smstemp = templateModel.TemplateContent;
                    //smstemp = smstemp.Replace("{username}", context.Session[RBSKeys.SESSION_SMS_CODE].ToString());
                    string projectName = (_pservice.GetProject(order.ProjectId)).ProjectName;
                    smstemp = smstemp.Replace("{peojectName}", (_pservice.GetProject(order.ProjectId)).ProjectName);
                    var msg = string.Empty;
                    //发送验证码   
                    var flag = SmsMessage.Send(order.ContactNumber, smstemp, 1, out msg); 
                }
                catch (Exception ex)
                {
                    MyLog.Write(ex.ToString());
                }
                Response.StatusCode = 200;
                Response.Write("OK");
            }
            else
            {
                MyLog.Write("ServiceCode=" + Request["ServiceCode"]);
                MyLog.Write("Version=" + Request["Version"]);
                MyLog.Write("Charset=" + Request["Charset"]);
                MyLog.Write("TraceNo=" + Request["TraceNo"]);
                MyLog.Write("SenderId=" + Request["SenderId"]);
                MyLog.Write("SendTime=" + Request["SendTime"]);
                MyLog.Write("RefundOrderNo=" + Request["RefundOrderNo"]);
                MyLog.Write("OriginalOrderNo=" + Request["OriginalOrderNo"]);
                MyLog.Write("Status=" + Request["Status"]);
                MyLog.Write("RefundAmount=" + Request["RefundAmount"]);
                MyLog.Write("RefundTransNo=" + Request["RefundTransNo"]);
                MyLog.Write("Ext1=" + Request["Ext1"]);
                MyLog.Write("SignType=" + Request["SignType"]);
                MyLog.Write("SignMsg=" + Request["SignMsg"]);
            }
        }
        #endregion
    }
}